import smtpd
from message import EmailMessage
import logging

class BasicServer(smtpd.SMTPServer):
  def __init__(self, handler, host='127.0.0.1', port=25):
    self.host = host
    self.port = port
    self.handler = handler
    smtpd.SMTPServer.__init__(self, (self.host, self.port), None)

  def process_message(self, peer, sender, recipients, data):
    logging.debug("incoming message from %s. sender: %s. recipients: %s" % (peer, sender, recipients))
    msg = EmailMessage.from_message_data(data)
    self.handler.process_message(msg)

def run_basic(handler, host, port):
  from django.conf import settings
  if not hasattr(settings, 'ROOT_MAILCONF'):
    from django.core.exceptions import ImproperlyConfigured
    raise ImproperlyConfigured("ROOT_MAILCONF setting is missing")
  import asyncore
  import sys
  logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
  BasicServer(handler(), host, port)
  asyncore.loop()
